package cn.edu.service.impl;

import cn.edu.mapper.DeptMapper;
import cn.edu.pojo.Dept;
import cn.edu.service.DeptService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author Mr.ma
 * @since 2022/12/7 19:41
 **/
@Service
public class DeptServiceImpl implements DeptService {
    @Resource
    private DeptMapper deptMapper;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    @Cacheable(cacheNames = "redis::dept", key = "#id")
    public Dept selectByIdAnn(int id) {
        Dept dept = deptMapper.selectById(id);
        return dept;
    }

    @Override
    @CachePut(cacheNames = "redis::dept", key = "#dept.did")
    public int updateByIdAnn(Dept dept) {
        int i = deptMapper.updateById(dept);
        return i;
    }

    @Override
    @CacheEvict(cacheNames = "redis::dept", key = "#id")
    public int deleteByIdAnn(int id) {
        int delete = deptMapper.deleteById(id);
        return delete;
    }

    @Override
    public int insert(Dept dept) {
        int insert = deptMapper.insert(dept);
        return insert;
    }

    @Override
    public Dept selectById(int id) {
        ValueOperations<String, Object> forValue = redisTemplate.opsForValue();
        Dept o = (Dept) forValue.get("dept::" + id);
        if (o != null){
            return o;
        }
        Dept dept = deptMapper.selectById(id);
        if (dept != null){
            forValue.set("dept::"+id,dept,20000, TimeUnit.SECONDS);
        }
        return dept;
    }

    @Override
    public int updateById(Dept dept) {
        int i = deptMapper.updateById(dept);
        ValueOperations<String, Object> forValue = redisTemplate.opsForValue();
        forValue.set("dept::"+dept.getDid(),dept,2000,TimeUnit.SECONDS);
        return i;
    }

    @Override
    public int deleteById(int id) {
        redisTemplate.delete("dept::" + id);
        int delete = deptMapper.deleteById(id);
        return delete;
    }

}
